package com.controller;

import com.ValidateGroupInterface.GroupIdInterface;
import com.ValidateGroupInterface.GroupParamInterface;
import com.exception.ValidateException;
import com.pojo.Group;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/group")
@Api(tags = "测试分组校验")
public class GroupController {

    /**
     * 使用@Validated注解，并指定组
     * 接收多个@Validated({GroupParamInterface.class,GroupParamInterface.class})
     */
    private static List<Group> list=new ArrayList<>();
    @PostMapping(value = "/insert")
    @ApiOperation("新增用户")
    public ResponseEntity<List<Group>> insert(@RequestBody @Validated({GroupParamInterface.class}) Group group, BindingResult result){
        if (result.hasErrors()){
            throw new ValidateException(result.getFieldErrors());
        }
        group.setId(list.size()==0?1:list.get(list.size()-1).getId()+1);
        list.add(group);
        return ResponseEntity.status(HttpStatus.OK).body(list);
    }

    /**
     * 使用@Validated注解指定校验组为GroupIdInterface
     */
    @PostMapping(value = "/update")
    @ApiOperation("修改用户")
    public ResponseEntity<List<Group>> update(@RequestBody @Validated({GroupIdInterface.class}) Group group,BindingResult result){
        if (result.hasErrors()){
            throw new ValidateException(result.getFieldErrors());
        }
       for (Group g:list){
            if (group.getId().intValue()==g.getId().intValue()){
                BeanUtils.copyProperties(group ,g);
            }
        }
        return ResponseEntity.status(HttpStatus.OK).body(list);
    }
}
